<?php
require 'vendor/autoload.php';

class CookiesManager{

	private $newspapersCookie;
	private $feedsXml;
	private $sourceArray;
	const cookieName = 'newspapers';

	public function setFeedsXml($feedsXml){
		$this->feedsXml = $feedsXml;
	}

	function setSourceArray($feedsXml){
		$this->sourceArray = simplexml_load_file($feedsXml);
	}

	private function cookieExists(){
		return isset($_COOKIE[self::cookieName]) && count(json_decode(stripslashes($_COOKIE[self::cookieName]))) == count($this->generateDefaultCookieString());
	}

	public function setupCookie(){
		$this->setSourceArray($this->feedsXml);
		if($this->cookieExists()){
			$this->newspapersCookie = json_decode(stripslashes($_COOKIE[self::cookieName]), true);
		} else {
			$this->generatePreferencesCookie();
			$this->newspapersCookie = $this->generateDefaultCookieString();
		}
	}

	public function getCookie(){
		return $this->newspapersCookie;
	}

	private function generatePreferencesCookie(){
		setcookie(self::cookieName, json_encode($this->generateDefaultCookieString()), $this->generateExpirationTime());
	}

	private function generateDefaultCookieString(){
		$newArray = array();

		foreach($this->sourceArray as $source){
			array_push($newArray, array("shortname" => (string) $source->shortName, "value" => '1'));

		}

		return $newArray;
	}

	private function generateExpirationTime(){
		return 60 * 60 * 24 * 365 + time();
	}

}

?>
